<template>
  <div ref="fixed" :style="containerStyle">
    <div :style="style">
      <slot />
    </div>
  </div>
</template>

<script>
import { NAV_TOP_DISTANCE } from '@/constants/index.js';

export default {
  name: 'FixedPage',

  props: {
    top: {
      type: Number,
      default: NAV_TOP_DISTANCE + 24
    },
    fixedStyle: {
      type: Object,
      default: () => {
        return {
          position: 'fixed',
          backdropFilter: 'blur(2px)'
        }
      }
    } 
  },

  data() {
    return {
      style: {},
      height: 0
    };
  },

  computed: {
    containerStyle() {
      const { height } = this;
      if (!height) return '';
      return { height: `${height}px` };
    }
  },

  mounted() {
    this.init();
  },

  beforeDestroy() {
    this.removeListeners();
  },

  methods: {
    init() {
      if (process.server) return;
      this.check();
      window.addEventListener('scroll', this.check);
    },
    removeListeners() {
      if (process.server) return;
      window.removeEventListener('scroll', this.check);
    },
    check() {
      const scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      const { height, top } = this.$el.getBoundingClientRect();
      this.height = height;
   
      if ((scrollTop !== 0) && (top < this.top)) {
        this.style =  {
          ...this.fixedStyle,
          top: `${this.top}px`
        } 
      } else {
        this.style = {};
      }
    }
  }
};
</script>
